package com.helmlabs.grouper.forms.dao;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

import com.helmlabs.grouper.core.Constants;
import com.helmlabs.grouper.core.util.HomeFolderUtil;
import com.helmlabs.grouper.forms.model.Form;
import com.thoughtworks.xstream.XStream;

public class FormDaoXml implements FormDao {

	public Form get(Long id) {
		try {
			File file = HomeFolderUtil.getFile("forms" + Constants.FILE_SEPARATOR + "form." + id + ".xml", false);
			FileInputStream fis = new FileInputStream(file);
			XStream xstream = new XStream();
			xstream.alias("form", Form.class);
			Form form = (Form)xstream.fromXML(fis);
			return form;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return null;
	}

	public Form save(Form form) {
		XStream xstream = new XStream();
		xstream.alias("form", Form.class);
		if (form.getId()==null){
			try {
				File file = HomeFolderUtil.getFile("forms", true);
				Long id = new Long(file.list().length);
				form.setId(id);
			} catch (Exception e){
				e.printStackTrace();
			}
		}
		
		try {
			File file = HomeFolderUtil.getFile("forms" + Constants.FILE_SEPARATOR + "form." + form.getId() + ".xml", false);
			System.out.println(file);
			if (!file.exists())
				file.createNewFile();
			FileOutputStream fos = new FileOutputStream(file);
			xstream.toXML(form, fos);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return form;
	}

}
